<template>
  <div class="hello_world">
    <div class="filter-forms">
      <div v-if="props.isDraft && data.length > 0" class="check-info">
        <a-checkbox
          :indeterminate="checkIndeterminate"
          :checked="isAllChecked"
          style="color: #999999"
          @change="onSelectAll"
        >
          全选
        </a-checkbox>
        <div class="delete-info">
          <span class="del-text" @click="didClickDelete">
            <i class="ifont-wid-Upload_icon_dete icon-del"></i>删除
          </span>
          <span class="checked-nums">已选{{ checkedList.length }}条</span>
        </div>
      </div>
      <!-- 表单-->
      <Form layout="inline" style="width: 100%">
        <div class="forms-box">
          <div class="left">
            <!-- 发布状态-->
            <Form.Item v-if="!props.isDraft" label="发布状态">
              <a-select
                style="width: 110px"
                placeholder="请选择"
                :value="valueState"
                :allow-clear="!!valueState"
                @change="showSearch"
              >
                <template #suffixIcon
                  ><img src="../../../assets/images/tab_icon_dow.png"
                /></template>
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="1">已发布</a-select-option>
                <a-select-option value="2">待生效</a-select-option>
                <!-- <a-select-option value="3">已结束</a-select-option>
          <a-select-option value="4">已撤回</a-select-option> -->
              </a-select>
            </Form.Item>
            <!-- 发布时间-->
            <Form.Item v-if="!props.isDraft" label="发布时间">
              <a-range-picker
                v-model:value="timeRange"
                style="width: 284px"
                value-format="YYYY-MM-DD"
                separator="至"
                :ranges="presetRanges"
                @change="onTimeRangeChange"
              >
                <template #suffixIcon
                  ><img src="../../../assets/images/icon_calendar.png"
                /></template>
              </a-range-picker>
            </Form.Item>
          </div>
          <div class="right">
            <Form.Item v-if="props.isDraft" label="创建时间">
              <a-range-picker
                v-model:value="draftTimeRange"
                value-format="YYYY-MM-DD "
                style="width: 284px"
                separator="至"
                @change="onDraftTimeRangeChange"
              >
                <template #suffixIcon
                  ><img src="../../../assets/images/icon_calendar.png"
                /></template>
              </a-range-picker>
            </Form.Item>
            <!-- 发布名称-->
            <Form.Item label="">
              <a-input
                v-if="identity === 8"
                v-model:value="queryParam.data.publicName"
                :maxlength="50"
                style="width: 204px"
                placeholder="请输入发布名称或发布人"
                @pressEnter="query"
              >
                <template #prefix>
                  <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i>
                </template>
              </a-input>
              <a-input
                v-else
                v-model:value="queryParam.data.publicName"
                :maxlength="50"
                style="width: 204px"
                placeholder="请输入发布名称"
                @pressEnter="query"
              >
                <template #prefix>
                  <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i>
                </template>
              </a-input>
            </Form.Item>
            <Form.Item class="formBtn">
              <a-button type="primary" class="btn" style="width: 64px" @click="query"
                >查询</a-button
              >
              <a-button class="ml-2" style="width: 64px; color: #999999" @click="resetForm(1)">
                重置
              </a-button>
            </Form.Item>
          </div>
        </div>
      </Form>
    </div>

    <!-- 已发布表格-->
    <div v-if="props.isDraft === 0" :class="data.length < 3 ? 'banner' : null">
      <InformationItem
        v-for="(item, index) in data"
        :key="index"
        :info-data="item"
        :info-id="item.id"
        @deleteInfo="deleteInfo"
        @recallInfo="recallInfo"
        @getPostList="getPostList"
      >
      </InformationItem>
      <Empty v-if="data.length === 0 && loading === false" :image="simpleImage" />
    </div>
    <!-- 草稿箱 -->
    <div v-else :class="data.length < 3 ? 'banner' : null">
      <DraftItem
        v-for="item in data"
        :key="item.id"
        :info-data="item"
        :info-id="item.id"
        @draftDeleteInfo="deleteInfo"
        @draftSelectInfo="draftSelectInfo"
      ></DraftItem>
      <Empty v-if="data.length === 0 && loading === false" :image="simpleImage" />
    </div>
    <!-- 分页-->
    <div v-if="isShowPagination" class="pagination">
      <span style="color: #999999; margin-right: 8px">共{{ total }}条</span>
      <a-pagination
        v-model:pageSize="pageSize"
        v-model:current="current"
        :page-size-options="pageSizeOptions"
        :show-size-changer="true"
        show-quick-jumper
        :total="total"
        @change="onChange"
      />
    </div>
    <div v-if="loading" class="loading">
      <Spin class="" tip="加载中..."></Spin>
    </div>
    <my-dialog
      :dialog-state="dialog.visible"
      :dialog-title="dialog.title"
      :dialog-width="dialog.width"
      :icon-type="dialog.warring"
      :show-icon="true"
      :draft-box-visible="false"
      :content-text="dialog.content"
      :sub-content-text="dialog.subContent"
      @handleCancel="dialogCancel"
      @handleOk="dialogOk"
    ></my-dialog>
  </div>
</template>

<script setup>
import { Form, Message, Empty, Spin } from 'ant-design-vue';
import MyDialog from '@/components/dialog/index.vue';
import InformationItem from './information-item';
import DraftItem from '../draft/draft-item';
import {
  ref,
  reactive,
  defineProps,
  onMounted,
  watch,
  defineExpose,
  defineEmits,
  computed,
  onActivated,
  onDeactivated
} from 'vue';
import { getReleaseInfoList } from '@/api/post-list';
import { deleteReleaseInfo, recallReleaseInfo } from '@/api/post-list.js';
import { checkCurrentUserIsAdmin, availableEquipment } from '@/api/user';
import store from '../../../store/index';
import dayjs from 'dayjs';

// 草稿箱选中条数
const checkedList = computed(() => data.value.filter(item => item.isSelected === true));
// 列表页数大于1时才显示分页
const isShowPagination = computed(() => Math.ceil(total.value / pageSize.value) > 1);
const emits = defineEmits(['haha', 'powerEmits']);
let identity = ref(); // 管理员值
let loading = ref();

// 页面被激活时
const isFirstLoadPage = ref(true);
onActivated(() => {
  if (!isFirstLoadPage.value) {
    getPostList();
  }
});
onDeactivated(() => {
  isFirstLoadPage.value = false;
});

onMounted(() => {
  let userAll = JSON.parse(localStorage.getItem('allUser'));
  // // // 学生 0；家长 1；教师 2；管理员 3
  let identitieList = userAll.identities;
  console.log(4444444, '身份权限', identitieList);
  let maxValue = Math.max.apply(null, identitieList);
  // let maxValue = 3;
  console.log(identitieList.includes(3));
  if (identitieList.includes(3)) {
    identity.value = 8;
    emits('powerEmits', 2);
    localStorage.setItem('equipmentDatas', 2);
    localStorage.setItem('identity', 8);
    store.commit('user/identity', 8);
    getPostList();
  } else {
    checkCurrentUserIsAdmin(localStorage.getItem('applicationId'))
      .then(res => {
        if (res.data.data) {
          localStorage.setItem('equipmentDatas', 2);
          emits('powerEmits', 2);
          localStorage.setItem('identity', 8);
          store.commit('user/identity', 8);
          identity.value = 8;
          getPostList();
        } else {
          getDevice();
        }
      })
      .catch(() => {
        localStorage.setItem('equipmentDatas', 1);
        emits('powerEmits', 1);
      });
  }
});
function getDevice() {
  let userAll = JSON.parse(localStorage.getItem('allUser'));
  // // // 学生 0；家长 1；教师 2；管理员 3
  let userId = userAll.user.businessId;
  localStorage.setItem('aa', userId);
  availableEquipment([String(userId)])
    .then(res => {
      if (res.data.data.length === 0) {
        localStorage.setItem('equipmentDatas', 1);
        emits('powerEmits', 1);
      } else {
        localStorage.setItem('equipmentDatas', 2);
        emits('powerEmits', 2);
        localStorage.setItem('identity', 2);
        store.commit('user/identity', 2);
        identity.value = 2;
        getPostList();
      }
    })
    .catch(() => {
      localStorage.setItem('equipmentDatas', 1);
      emits('powerEmits', 1);
    });
}

// 是否全选
const isAllChecked = ref(false);
let checkIndeterminate = ref(false);
function resetFn() {
  resetForm(1);
}
// 父组件调用的方法
function onIsAllChecked() {
  isAllChecked.value = false;
  checkIndeterminate.value = false;
}
defineExpose({
  onIsAllChecked,
  resetFn
});
// 弹窗相关
const dialog = reactive({
  type: '',
  title: '温馨提示',
  // content: `是否确认删除选中的${checkedList.value?.length}个草稿？`,
  subContent: '此操作不可恢复请谨慎操作！',
  warring: 'warring',
  visible: false,
  width: '406px'
});
// 暂无数据
const simpleImage = ref(require('@/assets/images/noData@2x.png'));
// 父组件传值
const props = defineProps({
  // 是否是草稿箱
  isDraft: { type: Number, default: 0 },
  releaseType: { type: String, default: '' }, // "" 全部； 0视频； 1 组图；2 文档； 3文章
  draftType: { type: String, default: '' }
});
watch(props, (newName, oldName) => {
  tebPostList();
});

// 发布时间区间
const timeRange = ref([dayjs(), dayjs()]);
// 预设时间范围
const presetRanges = ref({
  今天: [dayjs(), dayjs()],
  昨天: [dayjs().subtract(1, 'day'), dayjs().subtract(1, 'day')],
  近7天: [dayjs().subtract(7, 'day'), dayjs().subtract(1, 'day')]
});
// 草稿创建时间区间
const draftTimeRange = ref([]);
const draftStartDate = ref('');
const draftEndDate = ref('');

// 分页相关
const pageSizeOptions = ref(['10', '20', '30']);
const total = ref(0);
const pageSize = ref(10);
const pageNum = ref(1);
const current = ref(1);
function onChange() {
  document.documentElement.scrollTop = 0;
  queryParam.size = pageSize.value;
  queryParam.current = current.value;
  isAllChecked.value = false;
  checkIndeterminate.value = false;
  getPostList();
}
function toTops() {
  document.documentElement.scrollTop = 0;
}
// 表格数据
let data = ref([]);
// 请求参数
const queryParam = reactive({
  size: 10,
  current: 1,
  data: {
    identity: identity.value,
    infoStates: '1,2',
    isDraft: props.isDraft,
    infoType: '',
    publicName: ''
  }
});
const valueState = ref(''); // 状态默认值
// 发布状态
function showSearch(e, val) {
  current.value = 1;
  valueState.value = val?.value ?? '';
  queryParam.data.infoStates = val?.value ?? '1,2';
  queryParam.current = 1;
  getPostList();
}
function query() {
  queryParam.current = 1;
  current.value = 1;
  // pageNum.value = 1;
  getPostList();
}
// 切换调用列表方法
function tebPostList(e, a) {
  loading.value = true;
  queryParam.data.identity = identity.value;
  queryParam.data.publicName = queryParam.data.publicName.replace(/\s*/g, '');
  if (props.isDraft === 0) {
    queryParam.data.infoType = props.releaseType;
    queryParam.data.beginTime = dayjs(timeRange.value[0]).format('YYYY-MM-DD') + ' 00:00:00';
    queryParam.data.finishTime = dayjs(timeRange.value[1]).format('YYYY-MM-DD') + ' 23:59:59';
  } else {
    queryParam.data.infoType = props.draftType;
    queryParam.data.beginTime = draftStartDate.value;
    queryParam.data.finishTime = draftEndDate.value;
  }
  queryParam.current = 1;
  current.value = 1;
  getReleaseInfoList(queryParam)
    .then(res => {
      data.value = res.data.data.records;
      total.value = res.data.data.total;
      loading.value = false;
    })
    .catch(err => {
      console.log(err);
      loading.value = false;
    });
  // getPostList();
}

// 获取发布列表页数据
function getPostList(e, a) {
  loading.value = true;
  queryParam.data.identity = identity.value;
  queryParam.data.publicName = queryParam.data.publicName.replace(/\s*/g, '');
  if (props.isDraft === 0) {
    queryParam.data.infoType = props.releaseType;
    queryParam.data.beginTime = dayjs(timeRange.value[0]).format('YYYY-MM-DD') + ' 00:00:00';
    queryParam.data.finishTime = dayjs(timeRange.value[1]).format('YYYY-MM-DD') + ' 23:59:59';
  } else {
    queryParam.data.infoType = props.draftType;
    queryParam.data.beginTime = draftStartDate.value;
    queryParam.data.finishTime = draftEndDate.value;
  }
  queryParam.current = current.value;
  getReleaseInfoList(queryParam)
    .then(res => {
      let { records = [], total: totalNum = 0 } = res.data?.data || {};
      // 防止最后一页只有一条删除撤回数据为空的情况
      if (records.length === 0 && totalNum > 0) {
        queryParam.current--;
        current.value--;
        getPostList();
        return;
      }
      data.value = records;
      total.value = totalNum;
      loading.value = false;
      isAllChecked.value = false;
      checkIndeterminate.value = false;
    })
    .catch(err => {
      console.log(err);
      loading.value = false;
    });
  toTops();
}
// 删除发布信息
function deleteInfo(arr) {
  deleteReleaseInfo(arr)
    .then(res => {
      if (res.data.code !== 200) {
        Message.error(res.data.msg);
        return;
      }
      if (res.data.code === 200) {
        Message.success('删除成功');
        // return;
      }
      if (data.value.length === arr.length) {
        queryParam.current--;
        current.value--;
      }
      isAllChecked.value = false;
      checkIndeterminate.value = false;
      getPostList();
    })
    .catch(err => {
      Message.error(err);
    });
}
// 撤回发布信息
function recallInfo(arr) {
  recallReleaseInfo(arr)
    .then(res => {
      if (res.data.code === 200) {
        Message.success('该信息已经撤回');
      }
      getPostList();
    })
    .catch(err => {
      console.log(err);
    });
}
// 列表更改cheakbox
function draftSelectInfo(param) {
  let allSelect = true;
  data.value.forEach(item => {
    if (item.id === param.id) {
      item.isSelected = param.isSelected;
    }
    if (item.isSelected === false || item.isSelected === undefined) {
      allSelect = false;
    }
  });
  isAllChecked.value = allSelect;
  checkIndeterminate.value = checkedList.value.length > 0 && allSelect === false;
}

// 全选
function onSelectAll(e) {
  isAllChecked.value = e.target.checked;
  data.value.forEach(item => {
    item.isSelected = e.target.checked;
  });
  checkIndeterminate.value = false;
}
// 点击删除
function didClickDelete() {
  let draftsData = data.value.filter(elem => elem.isSelected);
  // 判断数组长度大于等于1时才能进行删除
  if (draftsData.length <= 0) {
    Message.warning('请至少选择一条删除的数据');
  } else {
    dialog.content = `是否确认删除选中的${checkedList.value?.length}个草稿？`;
    dialog.visible = true;
  }
}
// 点击取消
function dialogCancel() {
  dialog.visible = false;
  isAllChecked.value = false;
  checkIndeterminate.value = false;

  getPostList();
  setTimeout(() => {
    toTops();
  }, 10);
}
// 点击确定
function dialogOk() {
  dialog.visible = false;
  let draftsData = data.value.filter(elem => elem.isSelected);
  let arr = [];
  draftsData.map(item => arr.push(item.id));

  // 调用删除接口
  deleteInfo(arr);
  Message.success('删除成功');
  isAllChecked.value = false;
  checkIndeterminate.value = false;
  getPostList();
}
// 重置表单
function resetForm(values) {
  queryParam.size = '10';
  pageSize.value = '10';
  current.value = 1;
  queryParam.current = 1;
  queryParam.data.infoStates = '1,2';
  queryParam.data.publicName = '';
  timeRange.value = [dayjs(), dayjs()];
  draftTimeRange.value = [];
  draftStartDate.value = '';
  draftEndDate.value = '';
  isAllChecked.value = false;
  checkIndeterminate.value = false;
  valueState.value = '';
  if (values === 1) {
    tebPostList();
  }
}
function onTimeRangeChange(value, dateString) {
  current.value = 1;
  queryParam.current = 1;
  if (dateString[0] === '') {
    timeRange.value = [dayjs(), dayjs()];
  }
  getPostList();
}
function onDraftTimeRangeChange(value, dateString) {
  current.value = 1;
  queryParam.current = 1;
  draftStartDate.value = dateString[0] ? dateString[0] + ' 00:00:00' : '';
  draftEndDate.value = dateString[1] ? dateString[1] + ' 23:59:59' : '';
  getPostList();
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
